<template>
  <div v-loading="loading" element-loading-text="加载中..." class="new_out_storage">
    <div class="main">
      <header class="header">
        <div class="title">
          <div v-if="form.id" class="out_storage">
            <i class="iconfont icon-detail"></i>
            <div class="text">出库详情</div>
          </div>
          <div v-else class="new">新增出库</div>
        </div>

        <div class="btn_group">
          <h-plain-button @click="onSave">保存</h-plain-button>
          <h-plain-button v-permission="'outb_audit'" type="warning" @click="onCheck">
            {{ form.id ? '审核' : '保存并审核' }}
          </h-plain-button>
          <h-plain-button
            v-if="form.id"
            v-permission="'outb_reject'"
            type="error"
            @click="rejectDialogVisible = true"
          >
            驳回
          </h-plain-button>
          <h-button @click="onCancel">取消</h-button>
        </div>
      </header>

      <div class="divider_line"></div>

      <div class="body">
        <div ref="formContainerRef" class="form_container">
          <div v-if="route.params.id" class="title">
            <div class="text">出库编号:{{ detail.outboundNo }}</div>
            <h-status type="warning">待审核</h-status>
          </div>
          <el-form ref="formInstance" inline-message :model="form" :rules="rules" label-width="85">
            <div class="form_item">
              <!-- 单据类型 -->
              <el-form-item label="单据类型" prop="typeId">
                <el-select
                  v-model="form.typeId"
                  :loading="getWarehouseOutTypeOptionsLoading"
                  placeholder="单据类型"
                  filterable
                  clearable
                  :filter-method="handleGetWarehouseOutOptions"
                  disabled
                >
                  <el-option
                    v-for="(item, index) in warehouseOutTypeOptions"
                    :key="index"
                    :value="item.id"
                    :label="item.name"
                  />
                </el-select>
              </el-form-item>

              <!-- 单据来源 -->
              <el-form-item label="单据来源">
                <el-select v-model="form.source" placeholder="单据来源" clearable>
                  <el-option
                    v-for="(item, index) in sourceList"
                    :key="index"
                    :value="item.value"
                    :label="item.title"
                  />
                </el-select>
              </el-form-item>

              <!-- 单据日期 -->
              <el-form-item label="单据日期">
                <el-date-picker
                  v-model="form.createTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm"
                  :default-value="new Date()"
                />
              </el-form-item>
            </div>

            <!-- <div class="form_item"> -->
            <!-- 仓库类型 -->
            <!-- <el-form-item label="仓库类型" prop="storeType">
                <template #label>
                  <span style="display: flex; align-items: center">
                    仓库类型
                    <el-tooltip
                      content="选择对应出库仓类型后，只能从该类型仓库中出库物料"
                      placement="top"
                    >
                      <el-icon>
                        <QuestionFilled />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </template>
                <el-select v-model="form.storeType" placeholder="仓库类型" disabled>
                  <el-option
                    v-for="(item, index) in warehouseOutTypeList"
                    :key="index"
                    :value="item.value"
                    :label="item.title"
                  />
                </el-select>
              </el-form-item> -->

            <!-- 预计出库时间 -->
            <!-- <el-form-item label="预计出库时间">
                <el-date-picker
                  v-model="form.estimateTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm"
                  :default-value="new Date()"
                />
              </el-form-item> -->
            <!-- </div> -->

            <div class="form_item">
              <!-- 收货类型 -->
              <el-form-item label="收货类型" :prop="['receiptVo', 'receiptAddrType']">
                <el-select
                  v-model="form.receiptVo.receiptAddrType"
                  placeholder="收货类型"
                  @change="onReceiptTypeChange"
                >
                  <el-option
                    v-for="(item, index) in receiptAddressTypeList"
                    :key="index"
                    :value="item.value"
                    :label="item.title"
                  />
                </el-select>
              </el-form-item>

              <!-- 收获公司 -->
              <el-form-item
                v-if="form.receiptVo.receiptAddrType === 1"
                label="收货公司"
                :prop="['receiptVo', 'relationId']"
                :rules="[
                  {
                    required: true,
                    message: '收货公司不能为空',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <el-select-v2
                  v-model="form.receiptVo.relationId"
                  placeholder="请选择"
                  filterable
                  clearable
                  :options="receiptCustomerOptions"
                  :filter-method="handleGetReceiptCustomerList"
                  :loading="getReceiptCustomerListLoading"
                  @change="onReceiptCustomerChange"
                />
              </el-form-item>

              <!-- 收货仓库 -->
              <el-form-item
                v-else
                label="收货仓库"
                :prop="['receiptVo', 'relationId']"
                :rules="[
                  {
                    required: true,
                    message: '收货仓库不能为空',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <el-select-v2
                  v-model="form.receiptVo.relationId"
                  placeholder="请选择"
                  filterable
                  clearable
                  :options="warehouseAndPersonAddressOptions"
                  :filter-method="handleGetWarehouseAndPersonAddressList"
                  :loading="getWarehouseAndPersonAddressListLoading"
                  @change="onReceiptWarehouseChange"
                />
              </el-form-item>

              <!-- 收货手机 -->
              <el-form-item label="收货手机" :prop="['receiptVo', 'receiptPhone']">
                <el-input
                  v-model.trim="form.receiptVo.receiptPhone"
                  placeholder="收货手机"
                  maxlength="11"
                />
              </el-form-item>
            </div>

            <div class="form_item">
              <!-- 联系人 -->
              <el-form-item label="联系人" :prop="['receiptVo', 'receiptName']">
                <el-input
                  v-model.trim="form.receiptVo.receiptName"
                  clearable
                  placeholder="联系人"
                />
              </el-form-item>

              <!-- 收货地址 -->
              <el-form-item label="收货地址" :prop="['receiptVo', 'receiptProvince']">
                <single-address
                  ref="singleAddressInstance"
                  :address="receiptCustomerAddress"
                  @change="handleReceiptAddressChange"
                />
              </el-form-item>

              <!-- 详细地址 -->
              <el-form-item label="详细地址" :prop="['receiptVo', 'receiptAddress']">
                <el-input
                  v-model.trim="form.receiptVo.receiptAddress"
                  clearable
                  placeholder="详细地址"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                  type="textarea"
                />
              </el-form-item>
            </div>

            <div class="form_item">
              <!-- 单据备注 -->
              <el-form-item label="单据备注">
                <el-input
                  v-model.trim="form.remark"
                  clearable
                  placeholder="单据备注"
                  type="textarea"
                  resize="both"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="table-container">
          <div class="title">产品列表</div>
          <div class="table">
            <el-table
              ref="goodTableInstance"
              :border="true"
              :data="goodList"
              height="100%"
              show-summary
              :summary-method="getSummary"
              resizable
              stripe
              :row-class-name="getRowClassName"
            >
              <!-- 序号 -->
              <el-table-column label="序号" width="60" fixed="left" :align="'center'" type="index">
                <template #default="{ row, $index }">
                  {{ row.isFixed ? '' : $index }}
                </template>
              </el-table-column>

              <!-- 产品编号 -->
              <el-table-column prop="goodCode" show-overflow-tooltip label="产品编号" width="160" />

              <!-- 类型 -->
              <el-table-column show-overflow-tooltip label="类型" width="50">
                <template #default="{ row }">
                  <span v-if="!row.isFixed">{{ row.goodType === 1 ? '成品' : '物料' }}</span>
                </template>
              </el-table-column>

              <!-- 产品名称 -->
              <el-table-column prop="goodName" show-overflow-tooltip label="产品名称" width="140" />

              <!-- 型号 -->
              <!-- <el-table-column prop="goodModel" show-overflow-tooltip label="型号" width="160" /> -->

              <!-- 规格 -->
              <el-table-column prop="goodSpec" show-overflow-tooltip label="规格" width="160" />

              <!-- 品牌 -->
              <!-- <el-table-column
                prop="goodBrand"
                show-overflow-tooltip
                label="品牌"
                min-width="100"
              /> -->

              <!-- 分类 -->
              <el-table-column
                prop="goodClassify"
                show-overflow-tooltip
                label="分类"
                min-width="120"
              />

              <!-- 单位 -->
              <el-table-column prop="goodUnit" show-overflow-tooltip label="单位" width="60" />

              <!-- 发货仓库 -->
              <el-table-column label="发货仓库" width="150">
                <template #header>
                  发货仓库
                  <el-popover
                    placement="top"
                    :width="160"
                    :visible="warehouseMultipleChangePopoverVisible"
                  >
                    <h5 style="margin-bottom: 10px">批量填充发货仓库</h5>
                    <el-select
                      v-model="allWarehouseId"
                      placeholder="请选择发货仓库"
                      filterable
                      style="width: 100%"
                      :filter-method="handleGetWarehouseOptionList"
                    >
                      <el-option
                        v-for="(item, index) in warehouseOptionList"
                        :key="index"
                        :value="item.id"
                        :label="item.name"
                      />
                    </el-select>
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="onWarehouseMultipleChangeConfirm"
                      >
                        确定
                      </el-button>
                    </div>
                    <template #reference>
                      <span
                        style="
                          font-size: 11px;
                          background-color: #fff;
                          cursor: pointer;
                          color: #007cff;
                        "
                        @click="onWarehouseMultipleChangeClick"
                        >批量</span
                      >
                    </template>
                  </el-popover>
                </template>
                <template #default="{ row, $index }">
                  <el-select
                    v-if="!row.isFixed"
                    v-model="row.warehouseId"
                    placeholder="请选择仓库"
                    filterable
                    style="width: 100%"
                    :filter-method="handleGetWarehouseOptionList"
                    clearable
                    :class="{ selectError: isVerifyWarehouse && !row.warehouseId }"
                    :loading="getWarehouseOptionListLoading"
                    @change="handleWarehouseChange(row, $index)"
                  >
                    <el-option
                      v-for="(warehouse, index) in warehouseOptionList"
                      :key="index"
                      :value="warehouse.id"
                      :label="warehouse.name"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <!-- 仓位 -->
              <el-table-column label="仓位" width="150">
                <template #header>
                  仓位
                  <el-popover
                    placement="top"
                    trigger="click"
                    :width="160"
                    :visible="warehousePositionMultipleChangePopoverVisible"
                  >
                    <h5 style="margin-bottom: 10px">批量填充仓位</h5>
                    <el-select
                      v-model="allWarehousePositionId"
                      placeholder="请选择仓位"
                      :teleported="false"
                      filterable
                      :disabled="!multipleWarehousePositionSelectState"
                      :filter-method="handleMultipleGetWarehousePositionOptionList"
                    >
                      <el-option
                        v-for="(item, index) in goodList[0].warehousePositionOptionList"
                        :key="index"
                        :value="item.id"
                        :label="item.name"
                      />
                    </el-select>
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="onWarehousePositionMultipleChangeConfirm"
                      >
                        确定
                      </el-button>
                    </div>
                    <template #reference>
                      <span
                        style="
                          font-size: 11px;
                          background-color: #fff;
                          cursor: pointer;
                          color: #007cff;
                        "
                        @click="onWarehousePositionMultipleChangeClick"
                      >
                        批量
                      </span>
                    </template>
                  </el-popover>
                </template>
                <template #default="{ row, $index }">
                  <el-select
                    v-if="isWarehouseEnablePosition(row.warehouseId) && !row.isFixed"
                    v-model="row.warehousePositionId"
                    placeholder="请选择仓位"
                    filterable
                    :filter-method="
                      (val: string) => handleGetWarehousePositionOptionList(row.storeId, val, $index)
                    "
                    :loading="getWarehousePositionOptionListLoaing"
                    :class="{ selectError: isVerifyWarehouse && !row.warehousePositionId }"
                    @change="(id: string) => handleWarehousePositionChange(id, row, $index)"
                  >
                    <el-option
                      v-for="(item, index) in row.warehousePositionOptionList"
                      :key="index"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </template>
              </el-table-column>

              <!-- 可用库存 -->
              <el-table-column show-overflow-tooltip label="可用库存" width="95">
                <template #header>
                  <span>可用库存</span>
                  <el-tooltip content="可用库存 = 即时库存 - 占用库存" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                </template>
                <template #default="{ row }">
                  <span v-if="!row.isFixed">{{ row.goodStock }}</span>
                </template>
              </el-table-column>

              <!-- 选择条码 -->
              <el-table-column
                prop="stockCodeVos"
                show-overflow-tooltip
                label="选择条码"
                width="160"
              >
                <template #default="{ row }">
                  <template v-if="!row.isFixed">
                    <h-link v-if="row.snCodeList.length > 0" @click="handleSelectCodeClick(row)">{{
                      row.snCodeList[0].code
                    }}</h-link>
                    <h-link v-else @click="handleSelectCodeClick(row)">选择条码</h-link>
                  </template>
                </template>
              </el-table-column>

              <!-- 出库数量 -->
              <el-table-column prop="qty" show-overflow-tooltip label="出库数量" width="140">
                <template #header>
                  出库数量
                  <el-popover
                    placement="top"
                    trigger="click"
                    :width="160"
                    :visible="multipleChangeQtyPopoverVisible"
                  >
                    <h5 style="margin-bottom: 10px">批量填充出库数量</h5>
                    <el-input
                      v-model.trim="allQty"
                      placeholder="请输入出库数量"
                      maxlength="5"
                      @input="handleChangeAllQty"
                      @keyup.enter="onMultipleChangeQty"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="onMultipleChangeQty"
                      >
                        确定
                      </el-button>
                    </div>
                    <template #reference>
                      <span
                        style="
                          font-size: 11px;
                          background-color: #fff;
                          cursor: pointer;
                          color: #007cff;
                        "
                        @click="multipleChangeQtyPopoverVisible = !multipleChangeQtyPopoverVisible"
                      >
                        批量
                      </span>
                    </template>
                  </el-popover>
                </template>
                <template #default="{ row, $index }">
                  <el-input
                    v-if="!row.isFixed"
                    v-model.trim="row.qty"
                    maxlength="5"
                    placeholder="请输入出库数量"
                    @input="(qty: string) => handleChangeQty(qty, $index)"
                  />
                </template>
              </el-table-column>

              <!-- 单价 -->
              <!-- <el-table-column prop="unitPrice" label="单价" width="220">
                <template #header>
                  单价
                  <el-popover
                    placement="top"
                    :width="160"
                    :visible="multipleChangeUnitPricePopoverVisible"
                  >
                    <h5 style="margin-bottom: 10px">批量填充单价</h5>
                    <el-input
                      v-model.trim="allUnitPrice"
                      placeholder="请输入单价"
                      @input="allUnitPrice = amountForamt(allUnitPrice, 6)"
                      @keyup.enter="onChangeAllUnitPrice"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="onChangeAllUnitPrice"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span
                        style="
                          font-size: 11px;
                          background-color: #fff;
                          cursor: pointer;
                          color: #007cff;
                        "
                        @click="onMultipleChangeUnitPriceClick"
                        >批量</span
                      >
                    </template>
                  </el-popover>
                </template>
                <template #default="{ row }">
                  <el-input
                    v-if="!row.isFixed"
                    v-model.trim="row.price"
                    style="width: 180px"
                    placeholder="请输入单价"
                    @input="row.price = amountForamt(row.price, 6)"
                  >
                    <template #prepend>￥</template>
                  </el-input>
                </template>
              </el-table-column> -->

              <!-- 金额 -->
              <!-- <el-table-column prop="price" show-overflow-tooltip label="金额" width="160">
                <template #default="{ row }">
                  <span v-if="!row.isFixed"> ￥{{ (row.price * row.qty).toFixed(2) }} </span>
                </template>
              </el-table-column> -->

              <!-- 备注 -->
              <el-table-column prop="remark" show-overflow-tooltip label="备注" width="200">
                <template #default="{ row }">
                  <el-input
                    v-if="!row.isFixed"
                    v-model.trim="row.remark"
                    type="text"
                    clearable
                    placeholder="请输入备注"
                    maxlength="100"
                  />
                </template>
              </el-table-column>

              <!-- 紧急程度 -->
              <!-- <el-table-column show-overflow-tooltip label="紧急程度" width="140">
                <template #default="{ row }">
                  <el-select v-if="!row.isFixed" v-model="row.grade" placeholder="请选择紧急程度">
                    <el-option :value="1" label="一般" />
                    <el-option :value="2" label="紧急" />
                    <el-option :value="3" label="特别紧急" />
                  </el-select>
                </template>
              </el-table-column> -->

              <!-- 操作 -->
              <el-table-column width="90" fixed="right" label="操作">
                <template #default="{ row, $index }">
                  <h-link v-if="row.isFixed" @click="goodSelectModalVisible = true">
                    选择产品
                  </h-link>
                  <h-link v-else type="error" @click="handleDelGood($index)">删除</h-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </div>

    <good-select-modal
      v-model:visible="goodSelectModalVisible"
      :default-select-good-list="defaultSelectGoodList"
      @confirm="handleGoodSelectModalConfirm"
      @good-remove="handleGoodSelectModalRemove"
    />

    <sn-code-select-modal
      v-model:visible="selectCodeModalVisible"
      :good="currentSelectSnCodeGood"
      @select-sn-code="handleSelectSnCode"
    />

    <check-modal v-model:visible="checkModalVisible" :form="form" @update="onCheckModalUpdate" />

    <reject-modal
      v-model:visible="rejectDialogVisible"
      :warehouse-out-id="route.params.id as string || ''"
      @update="onRejectModalUpdate"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed } from 'vue'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import {
    FormInstance,
    ElDatePicker,
    ElTooltip,
    ElIcon,
    ElPopover,
    TableColumnCtx,
    TableInstance,
  } from 'element-plus'
  import _ from 'lodash'
  import { QuestionFilled } from '@element-plus/icons-vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Good } from './types'
  import { amountForamt } from '@/utils/tools'
  import routeComponentName from '@/config/route-component-name'
  import {
    useWarehouseOutForm,
    useGetWarehouseOutTypeOptions,
    useGetWarehouseOutReceiptCustomerList,
    useGetWarehouseAndPersonAddressList,
    useGetWarehouseOptionList,
    useGetWarehousePositionOptionList,
    useGetGoodStock,
    useGetWarehouseOutDetail,
    useGetMaterialListByWarehouseOutId,
  } from '@/services/pages/storage/useWarehouseOut'
  import { phone } from '@/utils/validate'
  import GoodSelectModal from '@/components/pages/Warehouse/out/GoodSelectModal.vue'
  import SnCodeSelectModal from '@/components/pages/Warehouse/out/SnCodeSelectModal.vue'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import CheckModal from '@/components/pages/Warehouse/out/CheckModal.vue'
  import RejectModal from '@/components/pages/Warehouse/out/RejectModal.vue'
  import fixedData from '@/config/fixed-data/warehouse/out-store'

  const { materialList, getMaterialListLoading, getMaterialList } =
    useGetMaterialListByWarehouseOutId()
  const { detail, getDetailLoading, getDetail } = useGetWarehouseOutDetail()
  const { form, formSaveLoading, resetForm, warehouseOutCreate } = useWarehouseOutForm()
  const {
    options: warehouseOutTypeOptions,
    getOptionsParam: getWarehouseOutTypeOptionsParam,
    getOptionsLoading: getWarehouseOutTypeOptionsLoading,
    getOptions: getWarehouseTypeOptions,
  } = useGetWarehouseOutTypeOptions()
  const {
    customerList: receiptCustomerList,
    getCustomerListParam: getReceiptCustomerListParam,
    getCustomerListLoading: getReceiptCustomerListLoading,
    getCustomer: getReceiptCustomerList,
  } = useGetWarehouseOutReceiptCustomerList()
  const {
    list: warehouseAndPersonAddressList,
    getListParam: getWarehouseAndPersonAddressListParam,
    getListLoading: getWarehouseAndPersonAddressListLoading,
    getList: getWarehouseAndPersonAddressList,
  } = useGetWarehouseAndPersonAddressList()
  const {
    warehouseOptionList,
    getWarehouseOptionListParam,
    getWarehouseOptionListLoading,
    getWarehouseOptionList,
  } = useGetWarehouseOptionList()
  const {
    warehousePositionOptionList,
    getWarehousePositionOptionListParam,
    getWarehousePositionOptionListLoaing,
    getWarehousePositionOptionList,
  } = useGetWarehousePositionOptionList()
  const { goodStock, getGoodStockParam, getWarehouseGoodStock } = useGetGoodStock()

  defineOptions({
    name: routeComponentName.storage.outStorageCreate,
  })

  // 驳回弹窗显示状态
  const rejectDialogVisible = ref(false)

  // 审核弹窗显示状态
  const checkModalVisible = ref(false)

  // 全局路由对象
  const router = useRouter()

  // 激活路由对象
  const route = useRoute()

  // 标签状态管理
  const tagsViewStore = useTagsViewStore()

  // 产品表格组件实例
  const goodTableInstance = ref<TableInstance | null>(null)

  /**
   * 是否校验仓库、仓位、条码是否有填写
   */
  const isVerifyWarehouse = ref(false)

  // 正在选择条码的产品
  const currentSelectSnCodeGood = ref<Good>({
    id: '',
    qty: '',
    price: '',
    remark: '',
    warehouseId: '',
    warehousePositionId: '',
    snCodeList: [],
    goodBrand: '',
    goodModel: '',
    goodName: '',
    goodSpecId: '',
    goodSpec: '',
    goodClassify: '',
    goodUnit: '',
    isFixed: false,
    goodType: 1,
    warehousePositionOptionList: [],
    goodStock: 0,
    goodId: '',
    goodCode: '',
    snCodeListBeforeCheck: [],
    grade: 1,
  })

  // 条码选择弹窗显示状态
  const selectCodeModalVisible = ref(false)

  // 批量填充单价弹出框显示状态
  const multipleChangeUnitPricePopoverVisible = ref(false)

  // 批量更新数量弹出框显示状态
  const multipleChangeQtyPopoverVisible = ref(false)

  // 所有数量
  const allQty = ref('')

  // 用于批量填充仓位
  const allWarehousePositionId = ref('')

  // 用于批量填充仓库
  const allWarehouseId = ref('')

  // 产品选择弹窗显示状态
  const goodSelectModalVisible = ref(false)

  // 产品列表
  const goodList = ref<Array<Good>>([])

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表单校验规则
  const rules = {
    typeId: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
    receiptVo: {
      receiptAddrType: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
      receiptName: [{ required: true, message: '收货人姓名', trigger: ['blur', 'change'] }],
      receiptPhone: [
        { required: true, message: '收货人手机号', trigger: ['blur', 'change'] },
        { validator: phone(form.value.receiptVo.receiptPhone), trigger: ['blur', 'change'] },
      ],
      receiptAddress: [{ required: true, message: '请输入详细地址', trigger: ['blur', 'change'] }],
      receiptProvince: [
        {
          required: true,
          validator: (rule, value, callback) => {
            const { receiptProvince } = form.value.receiptVo
            if (!receiptProvince) {
              callback(new Error('请选择地址'))
              return
            }
            callback()
          },
          trigger: ['blur', 'change'],
        },
      ],
    },
    storePositionId: [{ required: true, message: '仓库仓位', trigger: ['blur', 'change'] }],
    storeType: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }],
  }

  // 单据来源
  const sourceList = ref([
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    { title: '仓库移动端单据', value: 4 },
    { title: '第三方系统单据', value: 5 },
    { title: '网点移动端单据', value: 7 },
  ])

  // 出库仓类型
  const warehouseOutTypeList = ref([
    { title: '内部仓库', value: 0 },
    { title: '网点-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])

  // 收货地址类型
  const receiptAddressTypeList = ref([
    { title: '公司', value: 1 },
    { title: '网点仓库', value: 2 },
  ])

  // 收货公司地址
  const receiptCustomerAddress = computed(() => {
    return {
      province: form.value.receiptVo.receiptProvince,
      city: form.value.receiptVo.receiptCity,
      area: form.value.receiptVo.receiptArea,
      town: form.value.receiptVo.receiptTown,
    }
  })

  // 收货地址选择组件实例
  const singleAddressInstance = ref<InstanceType<typeof SingleAddress> | null>(null)

  /**
   * 公司下拉选项
   * 因为数量量过大，所以使用了虚拟选择器，这个选项列表就是给虚拟选择器用的
   */
  const receiptCustomerOptions = computed(() => {
    return receiptCustomerList.value.map((item) => {
      return {
        label: item.name,
        value: item.id,
        disabled: item.disabled,
      }
    })
  })

  /**
   * 收货仓库下拉选项
   * 因为数量量过大，所以使用了虚拟选择器，这个选项列表就是给虚拟选择器用的
   */
  const warehouseAndPersonAddressOptions = computed(() => {
    return warehouseAndPersonAddressList.value.map((item) => {
      return {
        label: item.name,
        value: item.id,
        disabled: item.disabled,
      }
    })
  })

  // 用于产品选择弹窗回显
  const defaultSelectGoodList = computed(() => {
    return goodList.value.slice(1).map((good) => {
      return {
        goodId: good.goodId,
        goodSpecId: good.goodSpecId,
      }
    })
  })

  // 批量选择仓库弹窗组件显示状态
  const warehouseMultipleChangePopoverVisible = ref(false)

  // 批量选择仓位弹窗组件显示状态
  const warehousePositionMultipleChangePopoverVisible = ref(false)

  /**
   * 获取批量仓位选择器的状态
   */
  const multipleWarehousePositionSelectState = computed(() => {
    const warehouseId = goodList.value[0].warehouseId
    const isAllWarehouseSameWarehouseId = goodList.value.every(
      (item) => item.warehouseId === warehouseId,
    )
    const isAllWarehouseEnablePosition = warehouseOptionList.value.some((item) => {
      if (item.id === goodList.value[0].warehouseId) {
        return item.enableStorePosition
      }
    })
    return isAllWarehouseSameWarehouseId && isAllWarehouseEnablePosition
  })

  // 用于批量填充单价
  const allUnitPrice = ref('')

  // 加载
  const loading = computed(() => {
    return formSaveLoading.value || getDetailLoading.value || getMaterialListLoading.value
  })

  /**
   * 单价批量填充点击时触发
   */
  const onMultipleChangeUnitPriceClick = () => {
    multipleChangeUnitPricePopoverVisible.value = !multipleChangeUnitPricePopoverVisible.value
  }

  /**
   * 获取仓位下拉选项
   * 批量选择仓位的搜索事件
   */
  const handleMultipleGetWarehousePositionOptionList = _.debounce(async (keyword: string) => {
    if (getWarehousePositionOptionListParam.value.name !== keyword) {
      getWarehousePositionOptionListParam.value.name = keyword
      await getWarehousePositionOptionList(goodList.value[0].warehouseId)
      goodList.value = goodList.value.map((good) => {
        return {
          ...good,
          warehousePositionOptionList: warehousePositionOptionList.value,
        }
      })
    }
  }, 600)

  /**
   * 点击批量选择仓库时触发
   */
  const onWarehouseMultipleChangeClick = () => {
    warehouseMultipleChangePopoverVisible.value = !warehouseMultipleChangePopoverVisible.value
  }

  /**
   * 点击批量选择仓位时触发
   */
  const onWarehousePositionMultipleChangeClick = () => {
    warehousePositionMultipleChangePopoverVisible.value =
      !warehousePositionMultipleChangePopoverVisible.value
  }

  /**
   * 获取出库类型下拉选项
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehouseOutOptions = _.debounce((keyword: string) => {
    if (getWarehouseOutTypeOptionsParam.value.name !== keyword) {
      getWarehouseOutTypeOptionsParam.value.name = keyword
      getWarehouseTypeOptions()
    }
  }, 600)

  /**
   * 收货地址类型更新事件
   */
  const onReceiptTypeChange = () => {
    if (form.value.receiptVo.receiptAddrType === 1) {
      getReceiptCustomerList()
    } else {
      getWarehouseAndPersonAddressList(form.value.receiptVo.receiptAddrType === 2 ? 1 : 0)
    }
    Object.assign(form.value.receiptVo, {
      relationId: '',
      receiptName: '',
      receiptPhone: '',
      receiptAddress: '',
      receiptProvince: '',
      receiptCity: '',
      receiptArea: '',
      receiptTown: '',
    })
    if (singleAddressInstance.value) {
      singleAddressInstance.value.clearAddress()
    }
  }

  /**
   * 获取收货公司
   * @param {String} keyword - 搜索关键字
   */
  const handleGetReceiptCustomerList = _.debounce((keyword: string) => {
    if (getReceiptCustomerListParam.value.name !== keyword) {
      getReceiptCustomerListParam.value.name = keyword
      getReceiptCustomerList()
    }
  }, 600)

  /**
   * 收货地址更新事件
   * @param {Object} address - 地址
   * @param {String} address.province - 省
   * @param {String} address.city - 市
   * @param {String} address.area - 区
   * @param {String} address.town - 镇
   */
  const handleReceiptAddressChange = (address: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    form.value.receiptVo.receiptProvince = address.province
    form.value.receiptVo.receiptCity = address.city
    form.value.receiptVo.receiptArea = address.area
    form.value.receiptVo.receiptTown = address.town
  }

  /**
   * 获取收货仓库
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehouseAndPersonAddressList = _.debounce((keyword: string) => {
    if (getWarehouseAndPersonAddressListParam.value.name !== keyword) {
      getWarehouseAndPersonAddressListParam.value.name = keyword
      getWarehouseAndPersonAddressListParam.value.id = ''
      getWarehouseAndPersonAddressList(form.value.receiptVo.receiptAddrType === 2 ? 1 : 0)
    }
  }, 600)

  /**
   * 产品列表滚动到指定位置
   * @param top - 指定沿 Y 轴滚动元素的像素数
   * @param left - 指定沿 X 轴滚动元素的像素数
   */
  const tableScrollToSpecifyPosition = (top = 0, left = 600) => {
    if (goodTableInstance.value) {
      goodTableInstance.value.scrollTo({
        top,
        left,
        behavior: 'smooth',
      })
    }
  }

  /**
   * 表单和表格校验
   */
  const formAndTableValidate = async () => {
    if (!formInstance.value) {
      return Promise.reject('')
    }

    try {
      await formInstance.value.validate()
      if (goodList.value.slice(1).length <= 0) {
        HMessageBox.error('请选择产品')
        return Promise.reject('请选择产品')
      }
      isVerifyWarehouse.value = true
      for (let i = 0; i < goodList.value.slice(1).length; i++) {
        const good = goodList.value.slice(1)[i]
        if (!good.warehouseId) {
          tableScrollToSpecifyPosition(i * 40)
          HMessageBox.error('请选择仓库')
          return Promise.reject('请选择仓库')
        }

        const warehouse = warehouseOptionList.value.find((option) => option.id === good.warehouseId)
        if (!!warehouse && warehouse.enableStorePosition && !good.warehousePositionId) {
          tableScrollToSpecifyPosition(i * 40)
          HMessageBox.error('请选择仓位')
          return Promise.reject('请选择仓位')
        }

        // if (good.goodType === 1 && good.snCodeList.length <= 0) {
        //   tableScrollToSpecifyPosition(i * 40)
        //   HMessageBox.error('请选择条码')
        //   return Promise.reject('请选择条码')
        // }
      }
    } catch (error) {
      return Promise.reject('')
    }
  }

  /**
   * 保存事件
   */
  const onSave = async () => {
    try {
      await formAndTableValidate()
      form.value.outBoundMaterialVos = goodList.value.slice(1).map((item) => {
        return {
          goodsId: item.goodId,
          goodsSpecId: item.goodSpecId,
          id: item.id || '',
          price: Number(item.price),
          qty: Number(item.qty),
          remark: item.remark,
          storeId: item.warehouseId,
          storePositionId: item.warehousePositionId,
          type: item.goodType,
          stockCodeVos: item.snCodeList.map((snCode) => {
            return {
              code: snCode.code,
            }
          }),
          grade: item.grade,
        }
      })
      const res = await warehouseOutCreate()
      if (res.code === 20000) {
        HMessage.success('创建出库单成功')
        tagsViewStore.delView(route.path)
        router.push({ path: '/storage/outb', query: { isUpdate: 1 } })
        resetForm()
        return
      }
      HMessageBox.error(res.message)
    } catch (error) {
      // error
    }
  }

  /**
   * 审核事件
   */
  const onCheck = async () => {
    try {
      await formAndTableValidate()
      form.value.outBoundMaterialVos = goodList.value.slice(1).map((item) => {
        return {
          goodsId: item.goodId,
          goodsSpecId: item.goodSpecId,
          id: item.id,
          price: Number(item.price),
          qty: Number(item.qty),
          remark: item.remark,
          storeId: item.warehouseId,
          storePositionId: item.warehousePositionId,
          type: item.goodType,
          stockCodeVos: item.snCodeList.map((snCode) => {
            return {
              code: snCode.code,
            }
          }),
          grade: item.grade,
        }
      })
      checkModalVisible.value = true
    } catch (error) {
      // error
    }
  }

  /**
   * 获取表格行的类名，主要用于第一行数据固定显示
   * @param {Object} data - 表格行数据
   */
  const getRowClassName = (data: { row: Good; rowIndex: number }) => {
    if (data.rowIndex === 0) {
      return 'fixed-row'
    }
  }

  /**
   * 产品选择弹窗确认事件
   * @param {Array<WarehouseOutGood>} goodSelectionList - 产品选择列表
   */
  const handleGoodSelectModalConfirm = (goodSelectionList: Array<WarehouseOutGood>) => {
    goodSelectionList.forEach((good) => {
      const index = goodList.value.findIndex(
        (item) => item.goodId === good.id && item.goodSpecId === good.specId,
      )
      if (index === -1) {
        goodList.value.push({
          isFixed: false,
          qty: '1',
          price: '1.00',
          remark: '',
          warehouseId: fixedData.send_store_id,
          warehousePositionId: '',
          snCodeList: [],
          warehousePositionOptionList: [],
          goodStock: 0,
          goodId: good.id,
          id: '',
          goodName: good.name,
          goodSpec: good.specName,
          goodSpecId: good.specId,
          goodType: good.goodsType,
          goodModel: good.model,
          goodBrand: good.brand,
          goodClassify: good.type,
          goodUnit: good.unit,
          goodCode: good.code,
          snCodeListBeforeCheck: [],
          grade: 1,
        })
      }
    })
  }

  /**
   * 产品列表初始化
   */
  const goodListInit = () => {
    goodList.value = [
      {
        id: '',
        qty: '',
        price: '',
        remark: '',
        warehouseId: '1844582195014586370',
        warehousePositionId: '',
        snCodeList: [],
        goodBrand: '',
        goodModel: '',
        goodName: '',
        goodSpecId: '',
        goodSpec: '',
        goodUnit: '',
        isFixed: true,
        goodType: 1,
        warehousePositionOptionList: [],
        goodStock: 0,
        goodId: '',
        goodClassify: '',
        goodCode: '',
        snCodeListBeforeCheck: [],
        grade: 1,
      },
    ]
  }

  /**
   * 产品选择弹窗删除事件
   * @param {Array<WarehouseOutGood>} goodRemoveList - 产品删除列表
   */
  const handleGoodSelectModalRemove = (goodRemoveList: Array<WarehouseOutGood>) => {
    goodRemoveList.forEach((item) => {
      const index = goodList.value.findIndex(
        (good) => good.goodId === item.id && good.goodSpecId === item.specId,
      )
      if (index >= 0) {
        goodList.value.splice(index, 1)
      }
    })
  }

  /**
   * 获取仓库下拉选项
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehouseOptionList = _.debounce((keyword: string) => {
    if (getWarehouseOptionListParam.value.name !== keyword) {
      getWarehouseOptionListParam.value.name = keyword
      getWarehouseOptionList(form.value.storeType)
    }
  }, 600)

  /**
   * 判断仓库是否开启了仓位
   * @param {String} id - 仓库id
   */
  const isWarehouseEnablePosition = (id: string) => {
    const warehouse = warehouseOptionList.value.find((item) => item.id === id)
    return warehouse && warehouse.enableStorePosition
  }

  /**
   * 列表仓库更新事件
   * @param {Good} good - 产品对象
   * @param {Number} index - 产品索引
   */
  const handleWarehouseChange = async (good: Good, index: number) => {
    if (good.warehouseId) {
      if (isWarehouseEnablePosition(good.warehouseId)) {
        await getWarehousePositionOptionList(good.warehouseId)
        goodList.value[index].warehousePositionOptionList = warehousePositionOptionList.value
      } else {
        getGoodStockParam.value = {
          storeId: good.warehouseId,
          storePositionId: good.warehousePositionId,
          goodsId: good.goodId,
          goodsSpecId: good.goodSpecId,
          type: good.goodType,
        }
        await getWarehouseGoodStock()
        goodList.value[index].price = goodStock.value.price.toFixed(2)
        goodList.value[index].goodStock = goodStock.value.systemStock
        if (goodStock.value.price <= 0) {
          goodList.value[index].price = '1.00'
        }
      }
    }
  }

  /**
   * 获取仓位下拉选项
   * @param {String} keyword - 搜索关键字
   */
  const handleGetWarehousePositionOptionList = _.debounce(
    async (good: Good, keyword: string, index: number) => {
      if (getWarehousePositionOptionListParam.value.name !== keyword) {
        getWarehousePositionOptionListParam.value.name = keyword
        await getWarehousePositionOptionList(good.warehouseId)
        goodList.value[index].warehousePositionOptionList = warehousePositionOptionList.value
      }
    },
    600,
  )

  /**
   * 批量填充价格和库存
   */
  const multipleFillPriceAndGoodStock = async () => {
    getGoodStockParam.value = {
      storeId: goodList.value[1].warehouseId,
      storePositionId: '',
      goodsId: goodList.value[1].goodId,
      goodsSpecId: goodList.value[1].goodSpecId,
      type: goodList.value[1].goodType,
    }
    await getWarehouseGoodStock()
    goodList.value.forEach((good, index) => {
      // 第一条数据仅仅只是用在固定住显示的，不一条产品数据
      if (index >= 1) {
        goodList.value[index].price = goodStock.value.price.toFixed(2)
        goodList.value[index].goodStock = goodStock.value.systemStock

        if (goodStock.value.price <= 0) {
          goodList.value[index].price = '1.00'
        }
      }
    })
  }

  /**
   * 仓库批量选择事件
   */
  const onWarehouseMultipleChangeConfirm = async () => {
    goodList.value = goodList.value.map((item) => {
      return {
        ...item,
        warehouseId: allWarehouseId.value,
      }
    })

    if (!isWarehouseEnablePosition(allWarehouseId.value)) {
      await multipleFillPriceAndGoodStock()
    } else {
      await getWarehousePositionOptionList(allWarehouseId.value)
      goodList.value = goodList.value.map((good) => {
        return {
          ...good,
          warehousePositionOptionList: warehousePositionOptionList.value,
        }
      })
    }
    warehouseMultipleChangePopoverVisible.value = false
  }

  /**
   * 仓位批量选择事件
   */
  const onWarehousePositionMultipleChangeConfirm = async () => {
    goodList.value = goodList.value.map((good) => {
      return {
        ...good,
        warehousePositionId: allWarehousePositionId.value,
      }
    })

    await multipleFillPriceAndGoodStock()
    warehousePositionMultipleChangePopoverVisible.value = false
  }

  /**
   * 仓位更新事件
   * @param {String} id - 选择的仓位id
   * @param {Good} good - 产品对象
   * @param {Number} index - 产品索引
   */
  const handleWarehousePositionChange = async (id: string, good: Good, index: number) => {
    goodList.value[index].warehousePositionId === id
    getGoodStockParam.value = {
      storeId: good.warehouseId,
      storePositionId: id,
      goodsId: good.goodId,
      goodsSpecId: good.goodSpecId,
      type: good.goodType,
    }
    await getWarehouseGoodStock()
    goodList.value[index].price = goodStock.value.price.toFixed(2)
    goodList.value[index].goodStock = goodStock.value.systemStock
    if (goodStock.value.price <= 0) {
      goodList.value[index].price = '1.00'
    }
  }

  /**
   * 批量更新数量
   */
  const onMultipleChangeQty = () => {
    goodList.value = goodList.value.map((item) => {
      return { ...item, qty: allQty.value }
    })
    multipleChangeQtyPopoverVisible.value = false
  }

  /**
   * 更新单价确定事件
   */
  const onChangeAllUnitPrice = () => {
    goodList.value = goodList.value.map((good) => {
      return {
        ...good,
        price: allUnitPrice.value,
      }
    })
  }

  /**
   * 数量更新事件
   * @param qty - 数量
   * @param index - 产品索引
   */
  const handleChangeQty = (qty: string, index: number) => {
    qty = qty.replace(/[^\d]/g, '')
    if (Number(qty) > 99999) {
      qty = '99999'
    }

    if (Number(qty) <= 0) {
      qty = '1'
    }

    goodList.value[index].qty = qty
  }

  /**
   * 数量批量更新事件
   */
  const handleChangeAllQty = () => {
    allQty.value = allQty.value.replace(/[^\d]/g, '')
    if (Number(allQty.value) > 99999) {
      allQty.value = '99999'
    }

    if (Number(allQty.value) <= 0) {
      allQty.value = '1'
    }

    goodList.value = goodList.value.map((good) => {
      return {
        ...good,
        qty: allQty.value,
      }
    })
  }

  /**
   * 表格合计
   */
  const getSummary = (param: { columns: TableColumnCtx<any>[]; data: Array<Good> }) => {
    const { columns, data } = param
    const sums: string[] = []
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[0] = '合计'
        return
      }

      if (column.property === 'qty') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += Number(good.qty)
          }
        })
        sums[index] = String(total)
      }

      if (column.property === 'unitPrice') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += Number(good.price) * 100
          }
        })
        sums[index] = (total / 100).toFixed(2)
      }

      if (column.property === 'price') {
        let total = 0
        data.forEach((good) => {
          if (!good.isFixed) {
            total += Number(good.qty) * Number(good.price)
          }
        })
        sums[index] = total.toFixed(2)
      }
    })

    return sums
  }

  /**
   * 产品删除事件
   * @param {Number} index - 产品索引
   */
  const handleDelGood = (index: number) => {
    const good = goodList.value.splice(index, 1)[0]
    if (good.id) {
      form.value.delOutBoundMaterialIds.push(good.id)
    }
  }

  /**
   * 条码选择事件
   * @param good - 产品对象
   */
  const handleSelectCodeClick = (good: Good) => {
    selectCodeModalVisible.value = true
    currentSelectSnCodeGood.value = good
  }

  /**
   * 条码选择事件
   * @param snCodeList - 条码列表
   */
  const handleSelectSnCode = (snCodeList: Array<{ id: string; code: string }>) => {
    const index = goodList.value.findIndex((item) => {
      return (
        item.goodId === currentSelectSnCodeGood.value.goodId &&
        item.goodSpecId === currentSelectSnCodeGood.value.goodSpecId
      )
    })
    if (index >= 0) {
      goodList.value[index].snCodeList = snCodeList
    }
  }

  /**
   * 填充表单
   */
  const fillForm = () => {
    form.value.id = detail.value.id
    form.value.createTime = detail.value.createTime
    form.value.delOutBoundMaterialIds = []
    form.value.estimateTime = detail.value.estimateTime
    form.value.receiptVo = {
      receiptAddrType: detail.value.receiptAddrType,
      receiptAddress: detail.value.receiptAddress,
      receiptArea: detail.value.receiptArea,
      receiptCity: detail.value.receiptCity,
      receiptName: detail.value.receiptName,
      receiptPhone: detail.value.receiptPhone,
      receiptProvince: detail.value.receiptProvince,
      receiptTown: detail.value.receiptTown,
      relationId: detail.value.relationId === '0' ? '' : detail.value.relationId,
      relationName: '',
      relationNo: detail.value.receiptNo,
      storePositionId: detail.value.storePositionId === '0' ? '' : detail.value.storePositionId,
    }
    form.value.remark = detail.value.remark
    form.value.reviewRemark = detail.value.reviewRemark
    form.value.source = detail.value.source
    form.value.storeType = detail.value.storeType
    form.value.typeId = detail.value.typeId
  }

  /**
   * 填充产品列表
   */
  const fillGoodList = async () => {
    for (let i = 0; i < materialList.value.length; i++) {
      const material = materialList.value[i]
      const warehouse = warehouseOptionList.value.find((item) => item.id === material.storeId)
      let _warehousePositionOptionList: Good['warehousePositionOptionList'] = []
      if (warehouse && warehouse.enableStorePosition) {
        await getWarehousePositionOptionList(material.storeId)
        _warehousePositionOptionList = warehousePositionOptionList.value
      }
      goodList.value.push({
        qty: material.qty.toString(),
        price: material.price.toFixed(2),
        remark: material.remark,
        warehouseId: material.storeId === '0' ? '' : material.storeId,
        warehousePositionId: material.storePositionId === '0' ? '' : material.storePositionId,
        isFixed: false,
        goodId: material.goodsId,
        snCodeList: material.stockCodeVos.map((item) => {
          return {
            code: item.code,
            id: item.codeId,
          }
        }),
        snCodeListBeforeCheck: material.stockCodeVos.map((item) => {
          return {
            code: item.code,
            id: item.codeId,
          }
        }),
        warehousePositionOptionList: _warehousePositionOptionList,
        id: material.id,
        goodStock: material.systemStock,
        goodBrand: material.goodsBrand,
        goodClassify: material.goodsType,
        goodCode: material.goodsCode,
        goodModel: material.goodsModel,
        goodName: material.goodsName,
        goodSpec: material.goodsSpecName,
        goodSpecId: material.goodsSpecId,
        goodType: material.type,
        goodUnit: material.goodsUnit,
        grade: material.grade,
      })

      // goodList.value = goodList.value.map((item) => {
      //   item.warehouseId = item.warehouseId ? item.warehouseId : fixedData.send_store_id
      //   return item
      // })
      for (let i = 0; i < goodList.value.length; i++) {
        const good = goodList.value[i]
        if (!good.isFixed) {
          getGoodStockParam.value = {
            storeId: good.warehouseId,
            storePositionId: good.warehousePositionId,
            goodsId: good.goodId,
            goodsSpecId: good.goodSpecId,
            type: good.goodType,
          }
          await getWarehouseGoodStock()
          goodList.value[i].goodStock = goodStock.value.systemStock
        }
      }
    }
  }

  /**
   * 审核弹窗更新事件
   */
  const onCheckModalUpdate = () => {
    resetForm()
    tagsViewStore.delView(route.path)
    switch (route.params.type) {
      case '1':
        router.push({ path: '/storage/outb', query: { isUpdate: 1 } })
        break
      case '2':
        router.push({ path: '/storage/order/material/out/list', query: { isUpdate: 1 } })
        break
    }
  }

  /**
   * 驳回弹窗更新事件
   */
  const onRejectModalUpdate = async () => {
    resetForm()
    tagsViewStore.delView(route.path)
    switch (route.params.type) {
      case '1':
        router.push({ path: '/storage/outb', query: { isUpdate: 1 } })
        break
      case '2':
        router.push({ path: '/storage/order/material/out/list', query: { isUpdate: 1 } })
        break
    }
  }

  /**
   * 取消事件
   */
  const onCancel = () => {
    resetForm()
    tagsViewStore.delView(route.path)
    switch (route.params.type) {
      case '1':
        router.push({ path: '/storage/outb', query: { isUpdate: 1 } })
        break
      case '2':
        router.push({ path: '/storage/order/material/out/list', query: { isUpdate: 1 } })
        break
    }
  }

  /**
   * 收货仓库更新事件
   * @param id - 收货仓库id
   */
  const onReceiptWarehouseChange = (id: string) => {
    const warehouse = warehouseAndPersonAddressList.value.find((item) => item.id === id)
    if (warehouse) {
      form.value.receiptVo.receiptPhone = warehouse.phone
      form.value.receiptVo.receiptName = warehouse.name
      form.value.receiptVo.receiptProvince = warehouse.province
      form.value.receiptVo.receiptArea = warehouse.area
      form.value.receiptVo.receiptCity = warehouse.city
      form.value.receiptVo.receiptAddress = warehouse.address
    }
  }

  /**
   * 收货公司更新事件
   * @param id - 公司id
   */
  const onReceiptCustomerChange = (id: string) => {
    const customer = receiptCustomerList.value.find((item) => item.id === id)
    if (customer) {
      form.value.receiptVo.receiptPhone = customer.phone
      form.value.receiptVo.receiptName = customer.name
      form.value.receiptVo.receiptProvince = customer.province
      form.value.receiptVo.receiptArea = customer.area
      form.value.receiptVo.receiptCity = customer.city
      form.value.receiptVo.receiptAddress = customer.address
    }
  }

  onMounted(async () => {
    goodListInit()
    getWarehouseTypeOptions()
    getReceiptCustomerList()

    if (route.query.documentSourceId) {
      form.value.typeId = route.query.documentSourceId as string
    }

    if (route.params.id) {
      await getDetail(route.params.id as string)
      fillForm()
      await getMaterialList(route.params.id as string)
      fillGoodList()
    }

    /**
     * TODO 收货仓库和发货仓库需要传入id去查询
     * 现在的做法是将每页显示多少条调高至1000条
     * 但是这种做法不好，因为数据量大时会造成性能问题
     */
    getWarehouseAndPersonAddressList(form.value.receiptVo.receiptAddrType === 2 ? 1 : 0)
    getWarehouseOptionList(form.value.storeType)
  })
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
